package com.weilive.core.event;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class EventDispatcher {
	
	private static ConcurrentHashMap<Class<? extends Event>, List<EventListener>> listeners = new ConcurrentHashMap<Class<? extends Event>, List<EventListener>>();

	public static void registerListener(EventListener listener, Class<? extends Event> c) {
		List<EventListener> listenerList = listeners.get(c);
		if (listenerList == null) {
			listenerList = new CopyOnWriteArrayList<EventListener>();
			listeners.put(c, listenerList);
		}
		listenerList.add(listener);
	}
	
	public static void removeListener(EventListener listener, Class<? extends Event> c) {
		List<EventListener> listenerList = listeners.get(c);
		if (listenerList != null) {
			listenerList.remove(listener);
		}
	}
	
	public static void removeListeners(Class<? extends Event> c) {
		listeners.remove(c);
	}
	
	public static void removeAllListeners() {
		listeners.clear();
	}
	
	public static void sendEvent(Event e) {
		List<EventListener> listenerList = listeners.get(e.getClass());
		if (listenerList != null) {
			for (EventListener listener : listenerList) {
				listener.onReceiveEvent(e);
			}
		}
	}
}
